package com.keepitsimple.core;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DispatcherServlet
 */
public class DispatcherServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DispatcherServlet()
	{
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public void init(final ServletConfig config) throws ServletException
	{
		// TODO Auto-generated method stub
		super.init(config);
		String scan_package = config.getInitParameter("scan_package");
		DispatcherServletHelper.init(scan_package);
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		request.setCharacterEncoding("utf-8");
		String path = request.getServletPath();// 获取请求action /addUser.action
		path = path.substring(1);// addUser.action
		String resultPage = "";
		if (DispatcherServletHelper.urls.containsKey(path))
		{
			ActionContext bean = DispatcherServletHelper.urls.get(path);
			bean.setRequest(request);
			bean.setResponse(response);
			Class<?> cla = bean.getCla();
			Object actionObject = bean.getAction();
			if (bean.getParamsType() != null)
			{
				BeanUtils beanUtils = new BeanUtils();
				Object[] params = beanUtils.getMethodParam(request, bean.getParamsType(),bean.getActionParamsName());
			
						try
						{
							resultPage = (String) cla.getMethod(bean.getMethodName(), bean.getParamsType()).invoke(actionObject, params);
						} catch (IllegalArgumentException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (SecurityException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IllegalAccessException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (InvocationTargetException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (NoSuchMethodException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					
			} 
			if (resultPage.length()>0&&bean.getResults().get(resultPage)!=null)
			{
				request.getRequestDispatcher(bean.getResults().get(resultPage)).forward(request, response);
			}else{
				throw new RuntimeException("没有配置转向页面");
			}
		}
	}

}
